package com.atguigu.spzx.product.util;

import com.atguigu.spzx.model.entity.product.Category;

import java.util.ArrayList;
import java.util.List;

public class CategoryUtil {


    public static List<Category> buildTree(List<Category> categoryList) {
        List<Category> treeList=new ArrayList<>();
        //需要组装属性结构
        for (Category category : categoryList) {
            if (category.getParentId()==0){
                //找到最顶的数据
                //组装完它的孩子分类
                //放入treeList结果数组
                treeList.add(findChildren(category,categoryList));
            }
        }
        return treeList;
    }

    private static Category findChildren(Category category, List<Category> categoryList) {
        for (Category children : categoryList) {
            if (children.getParentId().longValue()==category.getId().longValue()){
                //找到孩子
                //组装孩子的孩子,并加入数组;
                category.getChildren().add(findChildren(children,categoryList));
            }
        }

       category.setHasChildren(!category.getChildren().isEmpty());
        return category;
    }

}
